package com.daffodil.framework.shiro.redis;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;

/**
 * 
 * @author yweijian
 * @date 2021年4月1日
 * @version 1.0
 * @description
 */
public class ShiroRedisCache implements Cache<String, Object> {
	
	private ShiroRedisTemplate redisTemplate;
	
	private String prefix = "";

	private String getKey(String key){
		return prefix + key;
	}

	ShiroRedisCache(ShiroRedisTemplate redisTemplate, String prefix) {
		this.redisTemplate = redisTemplate;
		this.prefix = prefix;
	}

	@Override
	public Object get(String key) throws CacheException {
		if (key == null) {
			return null;
		}
		return redisTemplate.opsForValue().get(this.getKey(key));
	}

	@Override
	public Object put(String key, Object value) throws CacheException {
		if (key == null || value == null) {
			return null;
		}
		redisTemplate.opsForValue().set(this.getKey(key), value);
		return value;
	}

	@Override
	public Object remove(String key) throws CacheException {
		if (key == null) {
			return null;
		}
		key = this.getKey(key);
		Object value = redisTemplate.opsForValue().get(key);
		redisTemplate.delete(key);
		return value;
	}

	@Override
	public void clear() throws CacheException {
		redisTemplate.delete(this.keys());
	}

	@Override
	public int size() {
		return this.keys().size();
	}

	@Override
	public Set<String> keys() {
		return redisTemplate.keys(prefix + "*");
	}

	@Override
	public Collection<Object> values() {
		Set<String> keys = keys();
		List<Object> values = new ArrayList<Object>(keys.size());
		for (String k : keys) {
			values.add(redisTemplate.opsForValue().get(k));
		}
		return values;
	}
}
